﻿Imports System.IO
Imports System.IO.File
Imports System.Math
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.Windows.Forms.VisualStyles
Imports Cognex.VisionPro
Imports Cognex.VisionPro.CalibFix
Imports Cognex.VisionPro.ImageProcessing
Imports Cognex.VisionPro.PMAlign
Imports Cognex.VisionPro.ToolGroup
Imports CommonDLL.Common
Imports CommonDLL.Common.SocketHelper
Imports MySql.Data

Public Class FrmAddProd2
    Dim TextTorq(30) As System.Windows.Forms.TextBox
    Dim TextAngle(30) As System.Windows.Forms.TextBox
    Dim TextFeeder(30) As System.Windows.Forms.TextBox
    Dim f() As String

    '  Dim ToolPath As String = ""
    Dim pointNO As Integer = 0

    Dim CADPoint(32) As MITSUBISHI_Point
    Dim CADPointName(32) As String
    Dim flag(7) As Boolean

    Dim tmpfifo1 As CogAcqFifoTool
    Dim tmpfifo2 As CogAcqFifoTool
    Dim tmpfifo3 As CogAcqFifoTool
    Dim tmpPMAlign1 As CogPMAlignTool
    Dim tmpPMAlign2 As CogPMAlignTool
    Dim tmpPMAlign3 As CogPMAlignTool

    Dim tmpCalibCB1 As CogCalibCheckerboardTool
    Dim tmpCalibCB2 As CogCalibCheckerboardTool
    Dim tmpCalibCB3 As CogCalibCheckerboardTool

    Dim prePhoto As MITSUBISHI_Point

    Dim myImageSharp As CogImageSharpnessTool
    Dim sharpScore As Double
    Dim myFrameGrabbers As CogFrameGrabbers
    Dim myFrameGrabber As ICogFrameGrabber
    Dim myAcqFifo As ICogAcqFifo
    Dim sharp_NO As String

    '
    Dim TrainRate(2) As Double

    Dim trainAngle(2) As Double
    Dim HomeX(2) As Double
    Dim HomeY(2) As Double

    Dim Rate0 As Double = 511 / 659 '图像与现实框比例

    Dim RateZoom As Double = 1  '显示1 缩放

    ''  Dim RateZoom As Double = 1  '显示1 缩放
    '  Dim RateZoom As Double = 1 '显示2 缩放
    Dim RECTX1 As Double '起点X

    Dim RECTY1 As Double '起点Y
    Dim RECTX2 As Double '终点X
    Dim RECTY2 As Double '终点Y
    Dim GetRegion1 As Boolean = False
    Dim MoveRegion1 As Boolean = False
    Dim GetRegion2 As Boolean = False
    Dim MoveRegion2 As Boolean = False
    Dim RgR As Double
    Dim RgSideX As Double
    Dim RgSideY As Double
    Dim PhotoSU As Integer

    Private Sub Button_VisionMark1_Click(sender As Object, e As EventArgs) Handles Button_VisionMark1.Click
        'CogVisionControl1.SetTBCheck(gTBCheck(0), "CogCalibCheckerboardTool1", "CogPMAlignTool1")
        CogVisionControl1.SetTBCheck(gTBCheck(0), "CogCalibNPointToNPointTool1", "CogPMAlignTool1")
    End Sub

    Private Sub Button_SaveTool1_Click(sender As Object, e As EventArgs) Handles Button_SaveTool1.Click
        gTBCheck(0) = CogVisionControl1.GetTBCheck()
        Dim path As String = gProDataPath & "\" & TextBox_NewProdName.Text & "\TBCheck1.vpp"
        CogVisionControl1.SaveTBCheck(path)
        flag(5) = True

        AutoAddPhotoPoint(1).X = CStr(TextBox_PX.Text)
        AutoAddPhotoPoint(1).Y = CStr(TextBox_PY.Text)
        AutoAddPhotoPoint(1).Z = CStr(TextBox_PZ.Text)
        AutoAddPhotoPoint(1).C = CStr(TextBox_PC.Text)

        Dim ss(4) As String
        ss(1) = CStr(TextBox_PX.Text)
        ss(2) = CStr(TextBox_PY.Text)
        ss(3) = CStr(TextBox_PZ.Text)
        ss(4) = CStr(TextBox_PC.Text)

        'Dim DBpath As AccessHelper = New AccessHelper("Tool\" & TextBox_NewProdName.Text & "\photo_point.accdb")
        'Dim sql As String = " update " & " domino " & "set x=" & ss(1) & ",y=" & ss(2) & ",z=" & ss(3) & ",c=" & ss(4) & " where PointName=" & "'photo1robot'"
        'DBpath.HandleAccess(sql)
        Dim SQL As String
        SQL = " update " & " photo_point " & "set x=" & ss(1) & ",y=" & ss(2) & ",z=" & ss(3) & ",c=" & ss(4) & " where PointName=" & "'photo1robot' and Product='" & TextBox_NewProdName.Text & "'"
        HandleMysql(SQL)

        MsgBox("保存拍照点1")
    End Sub

    Private Sub FrmAddProd2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Timer1.Enabled = True
        Motor_flag = True
        Button_SVON.BackColor = Color.YellowGreen
        Button_SVOFF.BackColor = Color.WhiteSmoke
        AddProdflag = True

        Me.Size = New System.Drawing.Size(989, 538)
        InitControl() '初始化控件
        Button_NextStep.Enabled = True

        GetDirectFiles(gProDataPath) '获取产品名
        GroupBox1.Visible = False
        Dim i As Integer
        For i = 0 To 31
            CADPoint(i).X = 0
            CADPoint(i).Y = 0
            CADPoint(i).Z = 0
            CADPoint(i).C = 0
        Next
        CADPointName(0) = "photo1cad"
        Panel4.Visible = True
        AddProdflag = True

        Button_PrePoint.Enabled = False
        For i = 0 To 7
            flag(i) = False
        Next
        TabControl1.SelectedIndex = 0

        ComboBox_Tool.SelectedItem = 1

        ComboBox_OldProd.Focus()
        StepOK1 = False
        StepOK2 = False
        StepOK3 = False
        Try

            Dim sRobotInf As Object = New Char()
            Dim sRobotID As Object = New Char()
            Dim sName As Object = New Char()
            Dim sData As Object = New Char()
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try

        '
        RobotConnectTypeInit()
    End Sub

    Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
        If StepOK1 = True Then
            TextBox_status1.Text = "产品已经到位"
            TextBox_status1.BackColor = Color.Lime
            TextBox_status2.Text = "准备匹配模板"
        End If
        If StepOK2 = True Then
            TextBox_status2.Text = "自动匹配模板中,请等待..."
            TextBox_status2.BackColor = Color.Yellow
        End If
        'TextBox_Err.Text = FrmMain.TextBox_RBErr.Text
        If StepOK3 = True Then
            TextBox_status2.Text = "匹配模板完成!请示教点位。"
            TextBox_status2.BackColor = Color.Lime
        End If
    End Sub

    ''' <summary>
    ''' 初始化控件
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub InitControl()
        Label_ProdInfo.BackColor = Color.Yellow 'step1
        Label_ModelSet1.BackColor = Color.WhiteSmoke 'step2
        Label_ModelSet2.BackColor = Color.WhiteSmoke 'step3
        Label_ModelSet3.BackColor = Color.WhiteSmoke 'step4
        Label_PointWrite.BackColor = Color.WhiteSmoke 'step5
        Label_PointPara.BackColor = Color.WhiteSmoke 'step6
        Label_Complete.BackColor = Color.WhiteSmoke 'step7

        TextTorq(0) = TextBox_TorqAll
        TextAngle(0) = TextBox_AngleAll
        TextFeeder(0) = TextBox_FeederAll

        TextTorq(1) = TextBox_Torq1
        TextAngle(1) = TextBox_Angle1
        TextFeeder(1) = TextBox_feeder1

        TextTorq(2) = TextBox_Torq2
        TextAngle(2) = TextBox_Angle2
        TextFeeder(2) = TextBox_feeder2

        TextTorq(3) = TextBox_Torq3
        TextAngle(3) = TextBox_Angle3
        TextFeeder(3) = TextBox_feeder3

        TextTorq(4) = TextBox_Torq4
        TextAngle(4) = TextBox_Angle4
        TextFeeder(4) = TextBox_feeder4

        TextTorq(5) = TextBox_Torq5
        TextAngle(5) = TextBox_Angle5
        TextFeeder(5) = TextBox_feeder5

        TextTorq(6) = TextBox_Torq6
        TextAngle(6) = TextBox_Angle6
        TextFeeder(6) = TextBox_feeder6

        TextTorq(7) = TextBox_Torq7
        TextAngle(7) = TextBox_Angle7
        TextFeeder(7) = TextBox_feeder7

        TextTorq(8) = TextBox_Torq8
        TextAngle(8) = TextBox_Angle8
        TextFeeder(8) = TextBox_feeder8

        TextTorq(9) = TextBox_Torq9
        TextAngle(9) = TextBox_Angle9
        TextFeeder(9) = TextBox_feeder9

        TextTorq(10) = TextBox_Torq10
        TextAngle(10) = TextBox_Angle10
        TextFeeder(10) = TextBox_feeder10

        TextTorq(11) = TextBox_Torq11
        TextAngle(11) = TextBox_Angle11
        TextFeeder(11) = TextBox_feeder11

        TextTorq(12) = TextBox_Torq12
        TextAngle(12) = TextBox_Angle12
        TextFeeder(12) = TextBox_feeder12

        TextTorq(13) = TextBox_Torq13
        TextAngle(13) = TextBox_Angle13
        TextFeeder(13) = TextBox_feeder13

        TextTorq(14) = TextBox_Torq14
        TextAngle(14) = TextBox_Angle14
        TextFeeder(14) = TextBox_feeder14

        TextTorq(15) = TextBox_Torq15
        TextAngle(15) = TextBox_Angle15
        TextFeeder(15) = TextBox_feeder15

        TextTorq(16) = TextBox_Torq16
        TextAngle(16) = TextBox_Angle16
        TextFeeder(16) = TextBox_feeder16

        TextTorq(17) = TextBox_Torq17
        TextAngle(17) = TextBox_Angle17
        TextFeeder(17) = TextBox_feeder17

        TextTorq(18) = TextBox_Torq18
        TextAngle(18) = TextBox_Angle18
        TextFeeder(18) = TextBox_feeder18

        TextTorq(19) = TextBox_Torq19
        TextAngle(19) = TextBox_Angle19
        TextFeeder(19) = TextBox_feeder19

        TextTorq(20) = TextBox_Torq20
        TextAngle(20) = TextBox_Angle20
        TextFeeder(20) = TextBox_feeder20

        TextTorq(21) = TextBox_Torq21
        TextAngle(21) = TextBox_Angle21
        TextFeeder(21) = TextBox_feeder21

        TextTorq(22) = TextBox_Torq22
        TextAngle(22) = TextBox_Angle22
        TextFeeder(22) = TextBox_feeder22

        TextTorq(23) = TextBox_Torq23
        TextAngle(23) = TextBox_Angle23
        TextFeeder(23) = TextBox_feeder23

        TextTorq(24) = TextBox_Torq24
        TextAngle(24) = TextBox_Angle24
        TextFeeder(24) = TextBox_feeder24

        TextTorq(25) = TextBox_Torq25
        TextAngle(25) = TextBox_Angle25
        TextFeeder(25) = TextBox_feeder25

        TextTorq(26) = TextBox_Torq26
        TextAngle(26) = TextBox_Angle26
        TextFeeder(26) = TextBox_feeder26

        TextTorq(27) = TextBox_Torq27
        TextAngle(27) = TextBox_Angle27
        TextFeeder(27) = TextBox_feeder27

        TextTorq(28) = TextBox_Torq28
        TextAngle(28) = TextBox_Angle28
        TextFeeder(28) = TextBox_feeder28

        TextTorq(29) = TextBox_Torq29
        TextAngle(29) = TextBox_Angle29
        TextFeeder(29) = TextBox_feeder29

        TextTorq(30) = TextBox_Torq30
        TextAngle(30) = TextBox_Angle30
        TextFeeder(30) = TextBox_feeder30
        Dim i As Integer
        For i = 0 To 30
            TextTorq(i).Text = "0"
            TextAngle(i).Text = "0"
            TextFeeder(i).Text = "0"
        Next
        ComboBox_OldProd.Items.Clear()
        TextBox_status1.BackColor = Color.WhiteSmoke
        TextBox_status1.Text = "等待产品流入..."
        TextBox_status2.BackColor = Color.WhiteSmoke
        TextBox_status2.Text = ""
        ComboBox_FLG1.SelectedIndex = 0
        'Button_ExpoureOK1.Enabled = False
        'Button_ExpoureOK2.Enabled = False
    End Sub

    ''' <summary>
    ''' 获取目录下文件
    ''' </summary>
    ''' <param name="s"></param>
    ''' <remarks></remarks>
    Private Sub GetDirectFiles(ByVal s As String)
        '找出位于 s 根目录下的所有文件
        Try
            Dim i As Integer = 0
            Dim t As Collections.ObjectModel.ReadOnlyCollection(Of String) = My.Computer.FileSystem.GetFiles(s), k As String, name() As String
            ComboBox_OldProd.Items.Clear()
            For Each k In My.Computer.FileSystem.GetDirectories(s)
                ReDim Preserve f(i)
                f(i) = k
                Dim myFileInfo As New IO.FileInfo(f(i))
                name = Split(f(i), "\")
                ComboBox_OldProd.Items.Add(name(UBound(name))) '获取文件名
                i += 1
            Next
            If i > 0 Then
                ComboBox_OldProd.SelectedIndex = 0
            End If
        Catch

        End Try
    End Sub

    Private Sub Button_PreStep_Click(sender As Object, e As EventArgs) Handles Button_PreStep.Click
        If TabControl1.SelectedIndex > 0 Then
            TabControl1.SelectedIndex = TabControl1.SelectedIndex - 1
            If TabControl1.SelectedIndex = 0 Then
                Button_PreStep.Enabled = False
                Button_NextStep.Enabled = True
            Else
                Button_PreStep.Enabled = True
            End If
        End If
        Select Case TabControl1.SelectedIndex
            Case 0  '保存产品信息
                Label_ProdInfo.BackColor = Color.Yellow  'step1
                Label_ModelSet1.BackColor = Color.WhiteSmoke 'step2
                Me.Size = New System.Drawing.Size(989, 716)
                GroupBox1.Visible = False
            Case 1   '做模板1
                Label_ModelSet1.BackColor = Color.Yellow 'step2
                Label_ModelSet2.BackColor = Color.WhiteSmoke 'step3
                Me.Size = New System.Drawing.Size(989, 716)
                GroupBox1.Visible = True
            Case 2 '做模板2
                Label_ModelSet2.BackColor = Color.Yellow 'step2
                Label_PointWrite.BackColor = Color.WhiteSmoke 'step3
                Me.Size = New System.Drawing.Size(989, 716)
                GroupBox1.Visible = True
            Case 3  '示教点位
                Label_PointWrite.BackColor = Color.Yellow 'step3
                Label_PointPara.BackColor = Color.WhiteSmoke 'step4
                Me.Size = New System.Drawing.Size(989, 716)
                GroupBox1.Visible = True
            Case 4 '保存螺丝点信息
                Label_PointPara.BackColor = Color.Yellow 'step4
                Label_Complete.BackColor = Color.WhiteSmoke 'step5
                Me.Size = New System.Drawing.Size(989, 716)
                GroupBox1.Visible = False
        End Select
    End Sub

    Private Sub Button_Exist_Click(sender As Object, e As EventArgs) Handles Button_Exist.Click
        Me.Close()
    End Sub

    Private Sub Button_VisionMark2_Click(sender As Object, e As EventArgs) Handles Button_VisionMark2.Click
        CogVisionControl2.SetTBCheck(gTBCheck(1), "CogCalibCheckerboardTool1", "CogPMAlignTool1")
        'CogVisionControl2.SetTBCheck(gTBCheck(1), "CogCalibNPointToNPointTool1", "CogPMAlignTool1")

    End Sub

    Private Sub Button_SaveTool2_Click(sender As Object, e As EventArgs) Handles Button_SaveTool2.Click
        gTBCheck(1) = CogVisionControl2.GetTBCheck()
        Dim path As String = gProDataPath & "\" & TextBox_NewProdName.Text & "\TBCheck2.vpp"
        CogVisionControl2.SaveTBCheck(path)
        flag(6) = True

        AutoAddPhotoPoint(2).X = CStr(TextBox_PX.Text)
        AutoAddPhotoPoint(2).Y = CStr(TextBox_PY.Text)
        AutoAddPhotoPoint(2).Z = CStr(TextBox_PZ.Text)
        AutoAddPhotoPoint(2).C = CStr(TextBox_PC.Text)

        Dim ss(4) As String
        ss(1) = CStr(TextBox_PX.Text)
        ss(2) = CStr(TextBox_PY.Text)
        ss(3) = CStr(TextBox_PZ.Text)
        ss(4) = CStr(TextBox_PC.Text)

        'Dim DBpath As AccessHelper = New AccessHelper("Tool\" & TextBox_NewProdName.Text & "\photo_point.accdb")
        'Dim sql As String = " update " & " domino " & "set x=" & ss(1) & ",y=" & ss(2) & ",z=" & ss(3) & ",c=" & ss(4) & " where PointName=" & "'photo2robot'"
        'DBpath.HandleAccess(sql)

        Dim SQLk As String
        SQLk = " update " & " photo_point " & "set x=" & ss(1) & ",y=" & ss(2) & ",z=" & ss(3) & ",c=" & ss(4) & " where PointName=" & "'photo2robot' and Product='" & TextBox_NewProdName.Text & "'"
        HandleMysql(SQLk)

        MsgBox("保存拍照点2")
    End Sub

    Private Sub Button_NextStep_Click(sender As Object, e As EventArgs) Handles Button_NextStep.Click
        SaveData(TabControl1.SelectedIndex)
    End Sub

    ''' </summary>
    ''' <param name="page"></param>
    ''' <remarks></remarks>
    Private Sub SaveData(ByVal page As Integer)
        Dim paste_flag As Boolean
        paste_flag = True
        Select Case page
            Case 0  '保存产品信息
                Label_ProdInfo.BackColor = Color.Lime 'step2
                Label_ModelSet1.BackColor = Color.Yellow 'step3

                '复制产品，并获取检测工具数组
                If ComboBox_OldProd.Text = "" Then
                    MsgBox("相似产品未指定！")
                    GoTo d
                End If
                If TextBox_NewProdName.Text = "" Then
                    MsgBox("新产品名未指定！")
                    GoTo d
                End If
                If TextBox_PointCount.Text = "" Then
                    MsgBox("锁附螺丝颗数未指定！")
                    GoTo d
                End If

                GetDirectFiles(gProDataPath) '获取产品名

                Dim i As Integer
                For i = 0 To ComboBox_OldProd.Items.Count - 1
                    If ComboBox_OldProd.Items(i).ToString = TextBox_NewProdName.Text Then
                        Select Case MsgBox("已存在产品" & ComboBox_OldProd.Items(i).ToString & "，是否修改？", MsgBoxStyle.YesNo)
                            Case MsgBoxResult.Yes
                                '确定要执行的
                                paste_flag = False
                            Case MsgBoxResult.No
                                '取消要执行的
                                GoTo d
                        End Select
                    End If
                Next

                Try
                    '复制机种
                    If paste_flag = True Then
                        Dim name As String = TextBox_NewProdName.Text
                        Dim path As String = gProDataPath & "\" & ComboBox_OldProd.Text '& "\"
                        If Dir(path, FileAttribute.Directory) <> "" Then
                            My.Computer.FileSystem.CopyDirectory(path, gProDataPath & "\" & name)
                            CopyMysql(ComboBox_OldProd.Text, name)
                        End If
                    End If

                    '保存螺丝颗数和螺丝型号
                    Dim filepath = gProDataPath & "\" & TextBox_NewProdName.Text & "\"
                    Dim Para_num As Integer = FreeFile()
                    'Dim OpenParameter As Boolean = Exists(filepath & "Parameter.txt")
                    Dim PointCount As Integer = Val(TextBox_PointCount.Text)
                    Dim ScrewSN As String = TextBox_ScrewSN.Text
                    Dim NEWScrewPara As ScrewPara
                    NEWScrewPara.PointCount = PointCount
                    NEWScrewPara.ScrewSN = ScrewSN
                    NEWScrewPara.chuansong_yanshi = CurScrewPara.chuansong_yanshi

                    FileOpen(Para_num, filepath & "Parameter.txt", OpenMode.Random)
                    FilePut(Para_num, NEWScrewPara)
                    FileClose(Para_num)

                    FrmMain.TCmbPro.Text = TextBox_NewProdName.Text

                    'If MsgBox("保存停止延时？", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                    '    Dim Tvalue As Double = Val(TextBox_MotorDly.Text)
                    '    Dim sql As String = " update " & " TimerDelay " & "set TimeSet=" & Tvalue & " where TimerNO=" & "'Timer1'"
                    '    Dim DBpath As AccessHelper = New AccessHelper("Tool\" & TextBox_NewProdName.Text & "\PointPara.accdb")
                    '    DBpath.HandleAccess(sql)
                    'End If
                Catch ex As Exception
                    MsgBox(ex.Message)
                End Try
                '加载相机
                ' LoadCameraTool()

                '指定机器人工具(0,1,2,3,4,5)
                ComboBox_Tool.SelectedIndex = 1
                '指定机器人速度20（）
                ComboBox_speed.SelectedIndex = 8
                '指定机器人寸动距离
                ComboBox_stepType.SelectedIndex = 3
                Me.Size = New System.Drawing.Size(989, 716)
                GroupBox1.Visible = True

                StepOK2 = True
                StepOK3 = False

            Case 1   '做模板1
                '加载相机工具
                Label_ModelSet1.BackColor = Color.Lime 'step2
                Label_ModelSet2.BackColor = Color.Yellow 'step3
                If flag(5) = False Then
                    MsgBox("模板1数据未保存！")
                End If

            Case 2   '做模板2
                Label_ModelSet2.BackColor = Color.Lime 'step2
                Label_ModelSet3.BackColor = Color.Yellow
                If flag(6) = False Then
                    MsgBox("模板2数据未保存！")
                End If

                'ComboBox_Tool.SelectedIndex = 2
            Case 3  '做模板3
                Label_ModelSet3.BackColor = Color.Lime 'step3
                Label_PointWrite.BackColor = Color.Yellow 'step4
                If flag(7) = False Then
                    MsgBox("模板3数据未保存！")
                End If

                'ComboBox_Tool.SelectedIndex = 2
            Case 4  '示教点位
                Label_PointWrite.BackColor = Color.Lime 'step4
                Label_PointPara.BackColor = Color.Yellow 'step5
                pointNO = 2
                CADPointName(pointNO) = "set01"
                TextBox_pointName.Text = CADPointName(pointNO)
                Me.Size = New System.Drawing.Size(835, 716)
                GroupBox1.Visible = False

            Case 5 '保存螺丝点信息
                Label_PointPara.BackColor = Color.Lime
                Label_Complete.BackColor = Color.Lime 'step5
                SavePointPara()
                Button_NextStep.Enabled = False
        End Select
        If TabControl1.SelectedIndex < TabControl1.TabCount Then
            TabControl1.SelectedIndex = TabControl1.SelectedIndex + 1
            Button_PreStep.Enabled = True
        End If
d:
    End Sub

    ''' <summary>
    ''' 保存set01~30点位数据
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub SavePointPara()
        Dim i As Integer = 0
        Try

            Dim sql As String = "select * from PointPara where Product =" & "'" & TextBox_NewProdName.Text & "'"
            Dim table As DataSet = SearchMysql(sql)
            If table.Tables(0).Rows.Count < 10 Then
                MsgBox("产品不存在!")
                GoTo d
            End If
            'For i = 1 To 30
            '    If i < 10 Then
            '        sql = " update " & " PointPara " & "set torque=" & TextTorq(i).Text & ",angle=" & TextAngle(i).Text & ",feeder=" & TextFeeder(i).Text & ",disable=0" & " where PointName=" & "'set0" & i & "'"
            '    Else
            '        sql = " update " & " PointPara " & "set torque=" & TextTorq(i).Text & ",angle=" & TextAngle(i).Text & ",feeder=" & TextFeeder(i).Text & ",disable=0" & " where PointName=" & "'set" & i & "'"
            '    End If
            '    DBpath.HandleAccess(Sql)
            'Next
            For i = 1 To 30
                If i < 10 Then
                    sql = " update " & " PointPara " & "set torque=" & TextTorq(i).Text & ",angle=" & TextAngle(i).Text & ",feeder=" & TextFeeder(i).Text & ",disable=0" & " where PointName=" & "'set0" & i & "' and Product='" & TextBox_NewProdName.Text & "'"
                Else
                    sql = " update " & " PointPara " & "set torque=" & TextTorq(i).Text & ",angle=" & TextAngle(i).Text & ",feeder=" & TextFeeder(i).Text & ",disable=0" & " where PointName=" & "'set" & i & "' and Product='" & TextBox_NewProdName.Text & "'"
                End If
                HandleMysql(sql)
            Next

            flag(4) = True
            MsgBox("点位参数保存成功！")
d:
        Catch ex As Exception
            MsgBox("SavePointPara err:" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_VisionMark3_Click(sender As Object, e As EventArgs) Handles Button_VisionMark3.Click
        CogVisionControl3.SetTBCheck(gTBCheck(2), "CogCalibCheckerboardTool1", "CogPMAlignTool1")
        'CogVisionControl3.SetTBCheck(gTBCheck(2), "CogCalibNPointToNPointTool1", "CogPMAlignTool1")

    End Sub

    Private Sub Button_SaveTool3_Click(sender As Object, e As EventArgs) Handles Button_SaveTool3.Click
        gTBCheck(2) = CogVisionControl3.GetTBCheck()

        Dim path As String = gProDataPath & "\" & TextBox_NewProdName.Text & "\TBCheck3.vpp"
        CogVisionControl3.SaveTBCheck(path)
        flag(7) = True

        AutoAddPhotoPoint(3).X = CStr(TextBox_PX.Text)
        AutoAddPhotoPoint(3).Y = CStr(TextBox_PY.Text)
        AutoAddPhotoPoint(3).Z = CStr(TextBox_PZ.Text)
        AutoAddPhotoPoint(3).C = CStr(TextBox_PC.Text)

        Dim sql As String = ""
        'Dim DBpath As AccessHelper = New AccessHelper("Tool\" & TextBox_NewProdName.Text & "\photo_point.accdb")
        'sql = " update " & " domino " & "set x=" & AutoAddPhotoPoint(3).X & ",y=" & AutoAddPhotoPoint(3).Y & ",z=" & AutoAddPhotoPoint(3).Z & ",c=" & AutoAddPhotoPoint(3).C & " where PointName=" & "'photo3robot'"
        'DBpath.HandleAccess(Sql)

        Dim SQLl As String
        SQLl = " update " & " photo_point " & "set x=" & AutoAddPhotoPoint(3).X & ",y=" & AutoAddPhotoPoint(3).Y & ",z=" & AutoAddPhotoPoint(3).Z & ",c=" & AutoAddPhotoPoint(3).C & " where PointName=" & "'photo3robot' and Product='" & TextBox_NewProdName.Text & "'"
        HandleMysql(SQLl)

        MsgBox("保存扫码点")
        'MsgBox("保存拍照点3")
    End Sub

    Private Sub Button_Step2_Click(sender As Object, e As EventArgs) Handles Button_Step2.Click
        Try
            Vision_NG = ""
            If Button_Step2.BackColor = Color.Lime Then
                StepOK2 = False
                Button_Step2.BackColor = Color.WhiteSmoke
                Button_Step2.UseVisualStyleBackColor = True

                TextBox_status2.Text = ""
                TextBox_status2.BackColor = Color.WhiteSmoke
            Else
                '加载产品
                FrmMain.TCmbPro.Text = TextBox_NewProdName.Text
                FrmMain.InitSetting()
                FrmMain.initPro(FrmMain.TCmbPro.Text)
                Chanpin = TextBox_NewProdName.Text
                '指定机器人速度20（）
                ComboBox_speed.SelectedIndex = 8
                '跑自动匹配程序
                Button_Step2.BackColor = Color.Lime

                StepNO = "STEP4"
                Timer2.Enabled = True
                Globalfunc.SendDataNORePly(StepNO, "192.168.1.120", "2016", "UTF8")

            End If
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_TeachRB_Click(sender As Object, e As EventArgs) Handles Button_TeachRB.Click
        Button_TeachRB.BackColor = Color.Lime
        Panel4.Visible = True
        Button_TeachCAD.BackColor = Color.WhiteSmoke
        Button_TeachCAD.UseVisualStyleBackColor = True
        pointNO = 2
        TextBox_pointName.Text = "set01"
        TextBox_CADX.Text = CADPoint(pointNO).X
        TextBox_CADY.Text = CADPoint(pointNO).Y
        TextBox_CADZ.Text = CADPoint(pointNO).Z
        TextBox_CADC.Text = CADPoint(pointNO).C
        Try

            ComboBox_Tool.SelectedIndex = 2

            CADPointName(0) = "photo1cad"
            CADPoint(0) = AutoAddPhotoPoint(1)
            CADPointName(1) = "photo2cad"
            CADPoint(1) = AutoAddPhotoPoint(2)
            CADPointName(2) = "set01"
            Dim i As Integer
            For i = 2 To 31
                If i < 10 Then
                    CADPointName(i) = "set0" & (i - 1)
                Else
                    CADPointName(i) = "set" & (i - 1)
                End If
            Next

d:
        Catch ex As Exception
            MsgBox("OpenUploadProcess:" & ex.Message.ToString & ex.StackTrace.ToString)
        End Try

    End Sub

    Private Sub Button_AddX_Click(sender As Object, e As EventArgs) Handles Button_AddX.Click
        Try
            If Motor_flag = False Then
                MsgBox("机器人伺服OFF,请先打开先打开机器人伺服")
                Return
            End If

            Dim MoveDate As String
            Dim Revedates As String

            MoveDate = "X" + "," + CStr(ComboBox_stepType.SelectedItem) + "," + CStr(ComboBox_speed.SelectedItem) + "," + CStr(ComboBox_Tool.SelectedItem) + vbCrLf
            If GetRoborConnectType() = RobotConnectType.LongConnection Then
                Revedates = WriteDataAndReceive(MoveDate)
            Else
                Revedates = Globalfunc.SendData("192.168.1.120", "2016", MoveDate, "UTF8", "ASCII")
            End If
            If Revedates = "" Then
                Return
            End If
            Dim recdata() As String = Revedates.Split(",")
            TextBox_PX.Text = Val(recdata(0))
            TextBox_PY.Text = Val(recdata(1))
            TextBox_PZ.Text = Val(recdata(2))
            TextBox_PC.Text = Val(recdata(3))
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_DecX_Click(sender As Object, e As EventArgs) Handles Button_DecX.Click
        Try
            If Motor_flag = False Then
                MsgBox("机器人伺服OFF,请先打开先打开机器人伺服")
                Return
            End If

            Dim MoveDate As String
            Dim Revedates As String

            MoveDate = "X" + "," + CStr(-ComboBox_stepType.SelectedItem) + "," + CStr(ComboBox_speed.SelectedItem) + "," + CStr(ComboBox_Tool.SelectedItem) + vbCrLf
            If GetRoborConnectType() = RobotConnectType.LongConnection Then
                Revedates = WriteDataAndReceive(MoveDate)
            Else
                Revedates = Globalfunc.SendData("192.168.1.120", "2016", MoveDate, "UTF8", "ASCII")
            End If

            'ButtonUP(1, 0)
            If Revedates = "" Then
                Return
            End If
            Dim recdata() As String = Revedates.Split(",")
            TextBox_PX.Text = Val(recdata(0))
            TextBox_PY.Text = Val(recdata(1))
            TextBox_PZ.Text = Val(recdata(2))
            TextBox_PC.Text = Val(recdata(3))
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
        End Try

    End Sub

    Private Sub Button_AddY_Click(sender As Object, e As EventArgs) Handles Button_AddY.Click
        Try
            If Motor_flag = False Then
                MsgBox("机器人伺服OFF,请先打开先打开机器人伺服")
                Return
            End If

            Dim MoveDate As String
            Dim Revedates As String

            MoveDate = "Y" + "," + CStr(ComboBox_stepType.SelectedItem) + "," + CStr(ComboBox_speed.SelectedItem) + "," + CStr(ComboBox_Tool.SelectedItem) + vbCrLf
            If GetRoborConnectType() = RobotConnectType.LongConnection Then
                Revedates = WriteDataAndReceive(MoveDate)
            Else
                Revedates = Globalfunc.SendData("192.168.1.120", "2016", MoveDate, "UTF8", "ASCII")
            End If

            'ButtonUP(1, 0)
            If Revedates = "" Then
                Return
            End If
            Dim recdata() As String = Revedates.Split(",")
            TextBox_PX.Text = Val(recdata(0))
            TextBox_PY.Text = Val(recdata(1))
            TextBox_PZ.Text = Val(recdata(2))
            TextBox_PC.Text = Val(recdata(3))
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_DecY_Click(sender As Object, e As EventArgs) Handles Button_DecY.Click
        Try
            If Motor_flag = False Then
                MsgBox("机器人伺服OFF,请先打开先打开机器人伺服")
                Return
            End If

            Dim MoveDate As String
            Dim Revedates As String

            MoveDate = "Y" + "," + CStr(-ComboBox_stepType.SelectedItem) + "," + CStr(ComboBox_speed.SelectedItem) + "," + CStr(ComboBox_Tool.SelectedItem) + vbCrLf
            If GetRoborConnectType() = RobotConnectType.LongConnection Then
                Revedates = WriteDataAndReceive(MoveDate)
            Else
                Revedates = Globalfunc.SendData("192.168.1.120", "2016", MoveDate, "UTF8", "ASCII")
            End If

            'ButtonUP(1, 0)
            If Revedates = "" Then
                Return
            End If
            Dim recdata() As String = Revedates.Split(",")
            TextBox_PX.Text = Val(recdata(0))
            TextBox_PY.Text = Val(recdata(1))
            TextBox_PZ.Text = Val(recdata(2))
            TextBox_PC.Text = Val(recdata(3))
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_AddZ_Click(sender As Object, e As EventArgs) Handles Button_AddZ.Click
        Try
            If Motor_flag = False Then
                MsgBox("机器人伺服OFF,请先打开先打开机器人伺服")
                Return
            End If

            Dim MoveDate As String
            Dim Revedates As String
            MoveDate = "Z" + "," + CStr(ComboBox_stepType.SelectedItem) + "," + CStr(ComboBox_speed.SelectedItem) + "," + CStr(ComboBox_Tool.SelectedItem) + vbCrLf
            If GetRoborConnectType() = RobotConnectType.LongConnection Then
                Revedates = WriteDataAndReceive(MoveDate)
            Else
                Revedates = Globalfunc.SendData("192.168.1.120", "2016", MoveDate, "UTF8", "ASCII")
            End If

            'ButtonUP(1, 0)
            If Revedates = "" Then
                Return
            End If
            Dim recdata() As String = Revedates.Split(",")
            TextBox_PX.Text = Val(recdata(0))
            TextBox_PY.Text = Val(recdata(1))
            TextBox_PZ.Text = Val(recdata(2))
            TextBox_PC.Text = Val(recdata(3))
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_DecZ_Click(sender As Object, e As EventArgs) Handles Button_DecZ.Click
        Try
            If Motor_flag = False Then
                MsgBox("机器人伺服OFF,请先打开先打开机器人伺服")
                Return
            End If

            Dim MoveDate As String
            Dim Revedates As String
            MoveDate = "Z" + "," + CStr(-ComboBox_stepType.SelectedItem) + "," + CStr(ComboBox_speed.SelectedItem) + "," + CStr(ComboBox_Tool.SelectedItem) + vbCrLf
            If GetRoborConnectType() = RobotConnectType.LongConnection Then
                Revedates = WriteDataAndReceive(MoveDate)
            Else
                Revedates = Globalfunc.SendData("192.168.1.120", "2016", MoveDate, "UTF8", "ASCII")
            End If

            'ButtonUP(1, 0)
            If Revedates = "" Then
                Return
            End If
            Dim recdata() As String = Revedates.Split(",")
            TextBox_PX.Text = Val(recdata(0))
            TextBox_PY.Text = Val(recdata(1))
            TextBox_PZ.Text = Val(recdata(2))
            TextBox_PC.Text = Val(recdata(3))
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_DecC_Click(sender As Object, e As EventArgs) Handles Button_DecC.Click
        Try
            If Motor_flag = False Then
                MsgBox("机器人伺服OFF,请先打开先打开机器人伺服")
                Return
            End If

            Dim MoveDate As String
            Dim Revedates As String
            MoveDate = "C" + "," + CStr(ComboBox_stepType.SelectedItem) + "," + CStr(ComboBox_speed.SelectedItem) + "," + CStr(ComboBox_Tool.SelectedItem) + vbCrLf
            If GetRoborConnectType() = RobotConnectType.LongConnection Then
                Revedates = WriteDataAndReceive(MoveDate)
            Else
                Revedates = Globalfunc.SendData("192.168.1.120", "2016", MoveDate, "UTF8", "ASCII")
            End If

            'ButtonUP(1, 0)
            If Revedates = "" Then
                Return
            End If
            Dim recdata() As String = Revedates.Split(",")
            TextBox_PX.Text = Val(recdata(0))
            TextBox_PY.Text = Val(recdata(1))
            TextBox_PZ.Text = Val(recdata(2))
            TextBox_PC.Text = Val(recdata(3))
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_AddC_Click(sender As Object, e As EventArgs) Handles Button_AddC.Click
        Try
            If Motor_flag = False Then
                MsgBox("机器人伺服OFF,请先打开先打开机器人伺服")
                Return
            End If

            Dim MoveDate As String
            Dim Revedates As String
            MoveDate = "C" + "," + CStr(-ComboBox_stepType.SelectedItem) + "," + CStr(ComboBox_speed.SelectedItem) + "," + CStr(ComboBox_Tool.SelectedItem) + vbCrLf

            If GetRoborConnectType() = RobotConnectType.LongConnection Then
                Revedates = WriteDataAndReceive(MoveDate)
            Else
                Revedates = Globalfunc.SendData("192.168.1.120", "2016", MoveDate, "UTF8", "ASCII")
            End If


            'ButtonUP(1, 0)
            If Revedates = "" Then
                Return
            End If
            Dim recdata() As String = Revedates.Split(",")
            TextBox_PX.Text = Val(recdata(0))
            TextBox_PY.Text = Val(recdata(1))
            TextBox_PZ.Text = Val(recdata(2))
            TextBox_PC.Text = Val(recdata(3))
        Catch ex As Exception
            MsgBox(ex.StackTrace.ToString & vbCrLf & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_SVON_Click(sender As Object, e As EventArgs) Handles Button_SVON.Click
        Try
            Motor_flag = True
            Button_SVON.BackColor = Color.YellowGreen
            Button_SVOFF.BackColor = Color.WhiteSmoke

            StepNO = "STONN"
            Dim Revedates As String
            If GetRoborConnectType() = RobotConnectType.LongConnection Then
                Revedates = WriteDataAndReceive(StepNO)
            Else
                Globalfunc.SendDataNORePly(StepNO, "192.168.1.120", "2016", "UTF8")
                Revedates = Globalfunc.SendData("192.168.1.120", "2016", StepNO, "UTF8", "ASCII")
            End If
            'ButtonUP(1, 0)
            If Revedates = "" Then
                Return
            End If
            Dim recdata() As String = Revedates.Split(",")
            TextBox_PX.Text = Val(recdata(0))
            TextBox_PY.Text = Val(recdata(1))
            TextBox_PZ.Text = Val(recdata(2))
            TextBox_PC.Text = Val(recdata(3))
            MsgBox("机器人伺服打开")
        Catch ex As Exception
            MsgBox("机器人伺服打开错误：" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_SVOFF_Click(sender As Object, e As EventArgs) Handles Button_SVOFF.Click
        Motor_flag = False
        Button_SVON.BackColor = Color.WhiteSmoke
        Button_SVOFF.BackColor = Color.YellowGreen
        Try
            StepNO = "STOFF"
            If GetRoborConnectType() = RobotConnectType.LongConnection Then
                WriteDataAndReceive(StepNO)
            Else
                Globalfunc.SendDataNORePly(StepNO, "192.168.1.120", "2016", "UTF8")
            End If
            MsgBox("机器人伺服关闭")
        Catch ex As Exception
            MsgBox("机器人伺服关闭错误：" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub ComboBox_speed_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox_speed.SelectedIndexChanged
        Try
            Dim sSendData As String
            Dim lStatus As Integer
            Dim CommandCode As Integer = 404
            '
            sSendData = ComboBox_speed.Text
        Catch ex As Exception
            MsgBox("错误：" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_PrePoint_Click(sender As Object, e As EventArgs) Handles Button_PrePoint.Click
        If pointNO > 0 Then
            pointNO = pointNO - 1
            Button_NextPoint.Enabled = True
            Select Case pointNO
                Case 0
                    CADPointName(pointNO) = "photo1cad"
                    Button_PrePoint.Enabled = False
                    Exit Select
                Case 1
                    CADPointName(pointNO) = "photo2cad"
                    Exit Select
                Case Is <= 10
                    CADPointName(pointNO) = "set0" & (pointNO - 1)
                    Exit Select
                Case Is > 10
                    CADPointName(pointNO) = "set" & (pointNO - 1)

                    Exit Select
            End Select
        Else
            CADPointName(pointNO) = "photo1cad"
        End If
        TextBox_pointName.Text = CADPointName(pointNO)
        TextBox_CADX.Text = CADPoint(pointNO).X
        TextBox_CADY.Text = CADPoint(pointNO).Y
        TextBox_CADZ.Text = CADPoint(pointNO).Z
        TextBox_CADC.Text = CADPoint(pointNO).C
    End Sub

    Private Sub Button_NextPoint_Click(sender As Object, e As EventArgs) Handles Button_NextPoint.Click
        Button_PrePoint.Enabled = True
        If pointNO < 31 Then
            pointNO = pointNO + 1
            Select Case pointNO
                Case 0
                    CADPointName(pointNO) = "photo1cad"

                    Exit Select
                Case 1
                    CADPointName(pointNO) = "photo2cad"

                    Exit Select
                Case Is <= 10
                    CADPointName(pointNO) = "set0" & (pointNO - 1)
                    Exit Select
                Case Is > 10
                    CADPointName(pointNO) = "set" & (pointNO - 1)
                    If pointNO = 31 Then
                        Button_NextPoint.Enabled = False
                    End If
                    Exit Select
            End Select

        End If
        TextBox_pointName.Text = CADPointName(pointNO)
        TextBox_CADX.Text = CADPoint(pointNO).X
        TextBox_CADY.Text = CADPoint(pointNO).Y
        TextBox_CADZ.Text = CADPoint(pointNO).Z
        TextBox_CADC.Text = CADPoint(pointNO).C
    End Sub

    Private Sub Button_ReadPoint_Click(sender As Object, e As EventArgs) Handles Button_ReadPoint.Click
        TextBox_CADX.Text = TextBox_PX.Text
        TextBox_CADY.Text = TextBox_PY.Text
        TextBox_CADZ.Text = TextBox_PZ.Text
        TextBox_CADC.Text = TextBox_PC.Text
    End Sub

    Private Sub TextBox_CADX_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles TextBox_CADX.TextChanged
        CADPoint(pointNO).X = Val(TextBox_CADX.Text)
    End Sub

    Private Sub TextBox_CADY_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles TextBox_CADY.TextChanged
        CADPoint(pointNO).Y = Val(TextBox_CADY.Text)
    End Sub

    Private Sub TextBox_CADZ_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles TextBox_CADZ.TextChanged
        CADPoint(pointNO).Z = Val(TextBox_CADZ.Text)
    End Sub

    Private Sub TextBox_CADC_TextChanged(ByVal sender As Object, ByVal e As EventArgs) Handles TextBox_CADC.TextChanged
        CADPoint(pointNO).C = Val(TextBox_CADC.Text)
    End Sub

    Private Sub Button_PointWrite_Click(sender As Object, e As EventArgs) Handles Button_PointWrite.Click
        Try
            If TextBox_NewProdName.Text = "" Then
                MsgBox("新建的产品名未指定！")
                GoTo d
            End If
            'Dim SavePath As String = ToolPath & "\" & TextBox_NewProdName.Text & "\cad_point.accdb"
            Dim sql1 As String = "select * from cad_point where Product =" & "'" & TextBox_NewProdName.Text & "'"
            Dim table As DataSet = SearchMysql(sql1)
            Dim i As Integer
            'If File.Exists(SavePath) = True Then
            If table.Tables(0).Rows.Count > 10 Then
                For i = 0 To Val(TextBox_PointCount.Text) + 1     '31
                    'Dim sql As String = " update " & " domino " & "set x=" & CADPoint(i).X & ",y=" & CADPoint(i).Y & ",z=" & CADPoint(i).Z & ",c=" & CADPoint(i).C & " where PointName=" & "'" & CADPointName(i) & "'"
                    'Dim DBpath As AccessHelper = New AccessHelper("Tool\" & TextBox_NewProdName.Text & "\cad_point.accdb")
                    'DBpath.HandleAccess(sql)
                    Dim sql2 As String = ""
                    sql1 = " update " & " cad_point " & "set x=" & CADPoint(i).X & ",y=" & CADPoint(i).Y & ",z=" & CADPoint(i).Z & ",c=" & CADPoint(i).C & " where PointName=" & "'" & CADPointName(i) & "' and Product='" & TextBox_NewProdName.Text & "'"
                    sql2 = " update " & " robot_point " & "set x=" & CADPoint(i).X & ",y=" & CADPoint(i).Y & ",z=" & CADPoint(i).Z & ",c=" & CADPoint(i).C & " where PointName=" & "'" & CADPointName(i) & "' and Product='" & TextBox_NewProdName.Text & "'"
                    HandleMysql(sql1)
                    HandleMysql(sql2)
                Next
                flag(3) = True
                Button_NextStep.Enabled = True
                MsgBox("点位写入完成！")
            Else
                MsgBox("产品不存在！请检查Mysql数据库")
            End If
d:
        Catch ex As Exception
            MsgBox("点位写入发生错误：" & ex.Message.ToString)
        End Try
    End Sub

    Private Sub Button_AllSet_Click(sender As Object, e As EventArgs) Handles Button_AllSet.Click
        Try
            If TextBox_head.Text > 30 Or TextBox_head.Text < 1 Then
                MsgBox("设定值超出范围！")
                TextBox_head.Text = "1"
                GoTo d
            End If
            If TextBox_end.Text > 30 Or TextBox_end.Text < 1 Then
                MsgBox("设定值超出范围！")
                TextBox_end.Text = "30"
                GoTo d
            End If
            If TextBox_end.Text < TextBox_head.Text Then
                MsgBox("最大值小于最小值")
                TextBox_head.Text = "1"
                TextBox_end.Text = "30"
                GoTo d
            End If

            Dim i As Integer = 0
            For i = Val(TextBox_head.Text) To (TextBox_end.Text)
                TextTorq(i).Text = TextBox_TorqAll.Text
                TextAngle(i).Text = TextBox_AngleAll.Text
                TextFeeder(i).Text = TextBox_FeederAll.Text
            Next
d:
        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try
    End Sub

    Private Sub auto1(ByRef MySocket As Socket)
        Dim __time As DateTime = DateTime.Now

        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(0).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(0).Tools.Item("CogCalibCheckerboardTool1")
            'Dim tmpCalibCB As CogCalibNPointToNPointTool = gTBCheck(0).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(0).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(0).Tools.Item("CogPMAlignTool1")
            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                '  AppendInfoToTextBox("FrameGrabber")
                If True Then

                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        ' AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        ' AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        'AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            SecondCCDState = 0 '正常
                            ' AppendInfoToTextBox("tmpCalibCB.Run()")
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""
                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then

                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(0) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(0) = dTemp
                                    'AppendInfoToTextBox(" SendDataR(0) = dTemp")
                                    strSendData += dTemp2 & ","
                                Else
                                    strSendData += "999" + ","
                                    strSendData += "999" + ","
                                    strSendData += "229.9,"
                                    strSendData += "0"
                                    SendDataX(0) = 999.0
                                End If
                                'If tmpPmalign.Results.Count < 1 Then
                                '    Dim fileName As String = MachineInfo1.Machine_MSN & Format(DateAndTime.Now, "yyyyMMddHHmmss") & ".jpg"
                                '    Dim filePath As String = gVisionFailedPath & TextBox_CurPro.Text & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                '    YSPic(CogRecordDisplay3, tmpfifo0, filePath, fileName)
                                'End If
c:
                                If SecondCCDState = 2 Then
                                    strSendData += "999,999,0,0"
                                    SendDataX(0) = 999.0
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(0) = 999.0
                            End If
                            strSendData += "" ' vbCrLf
                            'log.WriteInfoTo_ResultLog_RichTextBox(FrmMain.RichTextBox_log, strSendData)
                            FrmMain.RichTextBox_log.AppendText(strSendData & vbCrLf)
                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(Format(SendDataX(0), "0.000") & "," & Format(SendDataY(0), "0.000") & "," & Format(SendDataR(0), "0.000") & vbCrLf)
                            MySocket.Send(byteSend)
                            'TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"
                            'recivePictrue1(tmpfifo0.OutputImage, tmpfifo0.Operator.FrameGrabber, tmpPmalign.CreateLastRunRecord)
                            CogRecordDisplay4.Image = tmpfifo0.OutputImage
                            CogRecordDisplay4.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay4.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                ' AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception

            MsgBox(ex.StackTrace.ToString)
        End Try

        'CadToRobot()

d:
    End Sub

    Private Sub auto2(ByRef MySocket As Socket)
        Dim __time As DateTime = DateTime.Now
        ' AppendInfoToTextBox("auto2 run")
        Dim ReturnXYR As returnXY
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(1).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(1).Tools.Item("CogCalibCheckerboardTool1")
            'Dim tmpCalibCB As CogCalibNPointToNPointTool = gTBCheck(1).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(1).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(1).Tools.Item("CogPMAlignTool1")
            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                ' AppendInfoToTextBox("FrameGrabber")
                If True Then
                    'If tmpfifo0.Operator.FrameGrabber.SerialNumber = SecondCCDSerNum Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        ' AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        'AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        '   AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            ' AppendInfoToTextBox("ForthCameraImageProcess tmpCalibCB.Run()")
                            SecondCCDState = 0 '正常
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then
                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(2) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(2) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(2) = dTemp
                                    '  AppendInfoToTextBox("SendDataR(2) = dTemp")
                                    strSendData += dTemp2 & ","
                                Else
                                    SendDataX(2) = 999
                                End If
                                'If tmpPmalign.Results.Count < 1 Then
                                '    Dim fileName As String = MachineInfo1.Machine_MSN & Format(DateAndTime.Now, "yyyyMMddHHmmss") & ".jpg"
                                '    Dim filePath As String = gVisionFailedPath & TextBox_CurPro.Text & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                '    YSPic(CogRecordDisplay4, tmpfifo0, filePath, fileName)
                                'End If

c:
                                If SecondCCDState = 2 Then
                                    strSendData += "999,999,0,0"
                                    SendDataX(2) = 999.0
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(2) = 999.0
                            End If
                            FrmMain.RichTextBox_log.AppendText(strSendData & vbCrLf)
                            'log.WriteInfoTo_ResultLog_RichTextBox(FrmMain.RichTextBox_log, strSendData)
                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(Format(SendDataX(2), "0.000") & "," & Format(SendDataY(2), "0.000") & "," & Format(SendDataR(2), "0.000") & vbCrLf)
                            MySocket.Send(byteSend)

                            ' TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay5.Image = tmpfifo0.OutputImage
                            CogRecordDisplay5.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay5.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                ' AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            'AppendInfoToTextBox(ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

d:
    End Sub

    Private Sub auto3(ByRef MySocket As Socket)
        Dim __time As DateTime = DateTime.Now
        ' AppendInfoToTextBox("auto2 run")
        Dim ReturnXYR As returnXY
        Try
            Dim tmpfifo0 As CogAcqFifoTool = gTBCheck(2).Tools.Item("相机设定")
            Dim tmpCalibCB As CogCalibCheckerboardTool = gTBCheck(2).Tools.Item("CogCalibCheckerboardTool1")
            'Dim tmpCalibCB As CogCalibNPointToNPointTool = gTBCheck(2).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpCogCalibCheckerboardTool As CogCalibNPointToNPointTool = gTBCheck(2).Tools.Item("CogCalibNPointToNPointTool1")
            Dim tmpPmalign1 As CogPMAlignTool = gTBCheck(2).Tools.Item("CogPMAlignTool1")
            Dim tmpPmalign As CogPMAlignTool = tmpPmalign1
            Dim strErrorInfo As String = ""
            Dim strSendData As String = ""
            Dim bHasObject As Boolean = False
            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                ' AppendInfoToTextBox("FrameGrabber")
                If True Then
                    'If tmpfifo0.Operator.FrameGrabber.SerialNumber = SecondCCDSerNum Then
                    tmpfifo0.Run()
                    If tmpfifo0.OutputImage Is Nothing Then
                        ' AppendInfoToTextBox(tmpfifo0.RunStatus.Exception.ToString)
                        'AppendInfoToTextBox(tmpfifo0.RunStatus.Message)
                        tmpfifo0.Run()
                        '   AppendInfoToTextBox("AcqBaseImage首次取相失败，再进行第二次取相")
                        If tmpfifo0.OutputImage Is Nothing Then
                            SecondCCDState = 2
                            GoTo c
                        Else
                            GoTo sucess
                        End If
                    Else
sucess:
                        If tmpfifo0.OutputImage IsNot Nothing Then
                            ' AppendInfoToTextBox("ForthCameraImageProcess tmpCalibCB.Run()")
                            SecondCCDState = 0 '正常
                            tmpCalibCB.Run()
                            tmpCogCalibCheckerboardTool.Run()
                            tmpPmalign1.Run()
                            Dim dTemp As Double = 0
                            Dim dTemp2 As String = ""

                            If tmpPmalign1.RunStatus.Result = CogToolResultConstants.Accept Then
                                If tmpPmalign.Results.Count > 0 Then
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationX.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataX(2) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = tmpPmalign.Results.Item(0).GetPose.TranslationY.ToString
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataY(2) = dTemp
                                    strSendData += dTemp2 & ","
                                    dTemp = 0
                                    dTemp += tmpPmalign.Results.Item(0).GetPose.Rotation / Acos(-1) * 180
                                    dTemp2 = Format(dTemp, "000.00")
                                    SendDataR(2) = dTemp
                                    '  AppendInfoToTextBox("SendDataR(2) = dTemp")
                                    strSendData += dTemp2 & ","
                                Else
                                    SendDataX(2) = 999
                                End If
                                'If tmpPmalign.Results.Count < 1 Then
                                '    Dim fileName As String = MachineInfo1.Machine_MSN & Format(DateAndTime.Now, "yyyyMMddHHmmss") & ".jpg"
                                '    Dim filePath As String = gVisionFailedPath & TextBox_CurPro.Text & "\" & Format(Date.Now.Date, "yyyyMMdd") & "\" & Chanpin & "\" & "Fail Image\"
                                '    YSPic(CogRecordDisplay4, tmpfifo0, filePath, fileName)
                                'End If

c:
                                If SecondCCDState = 2 Then
                                    strSendData += "999,999,0,0"
                                    SendDataX(2) = 999.0
                                End If
                            Else
                                strSendData += "999,0,0,0"
                                SendDataX(2) = 999.0
                            End If
                            FrmMain.RichTextBox_log.AppendText(strSendData & vbCrLf)
                            'log.WriteInfoTo_ResultLog_RichTextBox(FrmMain.RichTextBox_log, strSendData)
                            Dim byteSend As Byte() = Encoding.ASCII.GetBytes(Format(SendDataX(2), "0.000") & "," & Format(SendDataY(2), "0.000") & "," & Format(SendDataR(2), "0.000") & vbCrLf)
                            MySocket.Send(byteSend)

                            ' TSRest.Text = (DateTime.Now.Ticks - __time.Ticks) / 10000 & "ms"

                            CogRecordDisplay6.Image = tmpfifo0.OutputImage
                            CogRecordDisplay6.Fit()
                            If tmpfifo0.Operator.FrameGrabber IsNot Nothing Then
                                CogRecordDisplay6.Record = tmpPmalign.CreateLastRunRecord
                            End If
                        Else
                            SecondCCDState = 3
                        End If

                    End If
                Else
                    SecondCCDState = 1
                End If
            Else
                SecondCCDState = 2
                GoTo c
                ' AppendInfoToTextBox("未连接摄像机！")
            End If
        Catch ex As Exception
            'AppendInfoToTextBox(ex.StackTrace.ToString)
            MsgBox(ex.StackTrace.ToString)
        End Try

d:
    End Sub

    Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
        If RunQFlag = "5" Then
            RunQFlag = "0"
            auto1(RunQSocket)
        ElseIf RunQFlag = "6" Then
            RunQFlag = "0"
            auto2(RunQSocket)
        ElseIf RunQFlag = "7" Then
            RunQFlag = "0"
            auto3(RunQSocket)
        End If
    End Sub

    Private Sub FrmAddProd2_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
        AddProdflag = False
        Timer1.Enabled = False

        Me.Dispose()
    End Sub

    Private Sub Button_Step1_Click(sender As Object, e As EventArgs) Handles Button_Step1.Click
    End Sub

    Private Sub ComboBox_Tool_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ComboBox_Tool.SelectedIndexChanged

    End Sub

#Region "机械手连接方式"

    Private Sub RobotConnectTypeInit()
        CmbConnectType.Items.Clear()
        CmbConnectType.Items.AddRange(New Object() {"短连接", "长连接"})
        CmbConnectType.SelectedIndex = 0
    End Sub

    Private Function GetRoborConnectType() As RobotConnectType
        If CmbConnectType.SelectedIndex = 0 Then
            Return RobotConnectType.Shortlink
        Else
            Return RobotConnectType.LongConnection
        End If
    End Function

    Dim _robotClient As TcpClient

    Private Sub ConnectServer(ByVal ip As String, ByVal prot As String)

        If _robotClient Is Nothing Then
            _robotClient = New TcpClient()
            _robotClient.BeginConnect(IPAddress.Parse(ip), Convert.ToInt32(prot), AddressOf Connected, _robotClient)
        End If

    End Sub

    Private Sub Connected(iar As IAsyncResult)

    End Sub



    Private Function WriteDataAndReceive(ByVal data As String) As String
        If _robotClient Is Nothing Then
            Return ""
        End If
        Try
            Dim sendBytes As Byte() = Encoding.UTF8.GetBytes(data)
            _robotClient.Client.Send(sendBytes)
            _robotClient.ReceiveTimeout = Val(ReceiveTimeout.Text) * 1000
            Dim recBytes(4095) As Byte
            Dim bytes As Integer = _robotClient.Client.Receive(recBytes, recBytes.Length, SocketFlags.None)
            Return Encoding.UTF8.GetString(recBytes, 0, bytes)
        Catch ex As IOException
            MsgBox(ex.Message)
        End Try
        Return ""
    End Function

    Private Function IsSocketConnect(client As TcpClient) As Boolean
        If client Is Nothing OrElse client.Client Is Nothing Then
            Return False
        End If
        If Not client.Client.Connected OrElse client.Client.RemoteEndPoint Is Nothing Then
            Return False
        End If
        Dim blockingState As Boolean = client.Client.Blocking
        Try
            Dim tmp(0) As Byte
            client.Client.Blocking = False
            Dim bytesSent As Integer = client.Client.Send(tmp, 0, 1, SocketFlags.None)
            Return True
        Catch ex As SocketException
            Return ex.ErrorCode = 10035
        Finally
            client.Client.Blocking = blockingState
        End Try
    End Function

    Private Sub RobotClientTimer_Tick(sender As Object, e As EventArgs) Handles RobotClientTimer.Tick

        If _robotClient IsNot Nothing Then
            If IsSocketConnect(_robotClient) Then
                BtnRobotConnect.BackColor = Color.Lime
                BtnRobotConnect.Text = "连接成功"
            Else
                BtnRobotConnect.BackColor = Color.Red
                BtnRobotConnect.Text = "连接失败"
                _robotClient = Nothing
            End If
        End If
        ConnectServer("192.168.1.102", 2016)
    End Sub

    Private Sub BtnRobotConnect_Click(sender As Object, e As EventArgs) Handles BtnRobotConnect.Click
        ConnectServer("192.168.1.102", 2016)
    End Sub

#End Region

End Class